/** @jsx jsx */;
import {keyframes,ClassNames, css, jsx } from '@emotion/react'
import classNames from 'classnames';
import {useFloating} from '@floating-ui/react-dom-interactions';
import React, { useState } from 'react';
import {computePosition,flip, shift,offset,arrow} from '@floating-ui/dom';
const css_global=css`
#button{

}
#arrow {
  position: absolute;
  background: #333;
  width: 8px;
  height: 8px;
  transform: rotate(45deg);
}
#tooltip {
  position: absolute;
  background: #222;
  color: white;
  font-weight: bold;
  padding: 5px;
  border-radius: 4px;
  font-size: 90%;
  pointer-events: none;
}`
export default function App() {
  // const [open, setOpen] = useState(true);
  // const {x, y, reference, floating, strategy} = useFloating({
  //   open,
  //   onOpenChange: setOpen,
  // });
  const ref_arrow=React.createRef();
  const [state,setState]=React.useState({
    left:0
    ,top:0
    ,arrow_style:{}
    ,display:"none"
    });
  function update() {
    computePosition(button, tooltip,{
      placement: 'right',
      middleware: [
        offset(6),
        flip(),
        shift({padding: 5}),
        arrow({element: ref_arrow.current})
      ],
    }).then(({x, y, placement, middlewareData}) => {
      setState((state)=>({...state,left:x,top:y}));
      const {x: arrowX, y: arrowY} = middlewareData.arrow;
      const staticSide = {
        top: 'bottom',
        right: 'left',
        bottom: 'top',
        left: 'right',
      }[placement.split('-')[0]];
      console.log(arrowX,arrowY,staticSide)     ;
      setState((state)=>({...state,arrow_style:{left:arrowX != null ? arrowX+"px" : ''
        ,top: arrowY != null ? arrowY+"px" : ''
        ,right:'',bottom:'',[staticSide]: '-4px'}}));
    });
  }
  function showTooltip() {
    setState((state)=>({...state,display:"block"}));
    update();
  }
   
  function hideTooltip() {
    setState((state)=>({...state,display:"none"}));
  }
  React.useEffect(()=>{
    update();
  },[])
  //  ['mouseenter', showTooltip],
  // ['mouseleave', hideTooltip],
  // ['focus', showTooltip],
  // ['blur', hideTooltip],
  console.log(state)
  return (
    <div css={css_global}>
      <button onMouseEnter={showTooltip} 
        onMouseLeave={hideTooltip} 
        onFocus={showTooltip} 
        onBlur={hideTooltip} 
        id="button" aria-describedby="tooltip">
        My button
      </button>
      <div id="tooltip" style={{left:state.left,top:state.top,display:state.display}} role="tooltip">My tooltip very very long ............................
        <div id="arrow" style={state.arrow_style} ref={ref_arrow}></div>
      </div>
    </div>
  );
}